// +----------------------------------------------------------------------
// | CmsWing [ 美业管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 psi All rights reserved.
// +----------------------------------------------------------------------
// | Author: huang <2374266244@qq.com>
// +----------------------------------------------------------------------
'use strict';
import Base from './base.js';

export default class extends Base {
  /**
   * stock action
   * @return {Promise} []
   */

	// 新增单据
	async addstockorderAction(){
		let data = JSON.parse(this.post('data'));
		// 组合成订单表和订单详细表
		let ordersn
		switch (Number(data.orderinfo.ordertype)) {
			case 6:
				ordersn = await this.getordersn('RKD',6)
				break
			case 7:
				ordersn = await this.getordersn('CKD',7)
				break
		}

		let orderdata = {
			order_sn: ordersn,
			departmentid: this.userinfo.departmentid,
			operatorid: this.userinfo.id,
			addtime: Math.round(Date.parse(new Date())/1000),
			ordertype: data.orderinfo.ordertype,
			status: 0,
			totalnum: data.orderinfo.totalnum,
			remarks: data.orderinfo.remarks
		}	

		// 插入到订单表
		let model = this.model('or_shop_stockorder');
		await model.transaction(async()=>{
			try{
				let resorder = await model.add(orderdata);
				let orderinfo = [];
				for (var i = data.list.length - 1; i >= 0; i--) {
					orderinfo.push({
						departmentid: this.userinfo.departmentid,
						orderid: resorder,
						goodsid: data.list[i].id,
						goodsname: data.list[i].name,
						num: data.list[i].num
					})
				};

				let resorderinfo = await this.model('or_shop_stockorderinfo').db(model.db()).addMany(orderinfo);

				if (resorder && resorderinfo) {
					model.commit();
					return this.success({data:200, info:'操作成功！'});
				} else {
					model.rollback();
					return this.fail("操作失败！");
				}
			}catch(e){
				model.rollback();
				return this.fail("操作失败！");
			}
		})
	}

	// 出入库单据列表
	async orderlistAction(){
		let page = this.post();
		let pages = page.pages;
		let limits = page.limits;
		let search = page.search;
		let zt = page.zt;
		let orid = this.userinfo.departmentid;

		let data = await this.model('or_shop_stockorder')
		.alias('o')
		.field('o.*, a.name as aname, oa.name as oname')
		.join('`think_or_admin` a on a.id = o.operatorid')
		.join('`think_or_admin` oa on oa.id = o.auditorid')
		.where({'o.departmentid':orid, 'o.ordertype':['IN',[6,7]], 'o.status': zt, 'o.order_sn|a.name': ['like', '%'+search+'%']})
		.page(pages, limits)
		.order('o.addtime desc')
		.countSelect();

		return this.json(data);
	}

	// 单据信息
	async orderinfoAction(){
		let id = this.post('id');
		let orderinfo = await this.model('or_shop_stockorder').where({id:id}).find();
		let orderlist = await this.model('or_shop_stockorderinfo').where({orderid:id}).select();
		let data = {
			orderinfo:orderinfo,
			orderlist:orderlist,
		}
		return this.json(data);
	}

	// 删除单据
	async deletestockorderAction(){
		let id = this.post('id');

		// 判断单据是否已经审核
		let orderinfo = await this.model('or_shop_stockorder').where({id:id}).find();
		if(orderinfo.status == 1){
			return this.fail("该订单已经被审核，不能删除！");
		}

		//删除操作
		let model = this.model('or_shop_stockorder');
		await model.transaction(async()=>{
			try{
				let ores = await model.where({id:id}).delete();
				// 删除附属表
				let ires = await this.model('or_shop_stockorderinfo').db(model.db()).where({orderid:id}).delete();
				if (ores && ires) {
					model.commit();
					return this.success({data:200, info:'操作成功！'});
				} else {
					model.rollback();
					return this.fail("操作失败！");
				}
			}catch(e){
				await model.rollback();
				return this.fail("操作失败！");
			}
		});
	}
	// 审核单据
	async reviewstockorderAction(){
		let id = this.post('id');

		// 判断单据是否已经审核
		let orderinfo = await this.model('or_shop_stockorder').where({id:id}).find();
		let orderlist = await this.model('or_shop_stockorderinfo').where({orderid:id}).select();

		if(orderinfo.status == 1){
			return this.fail("该订单已经被审核！");
		}
		// 审核单据要做那些工作  1.改变单据状态，2.改变商品库存， 3.记录库存日志

		// 操作
		let model = this.model('or_shop_stockorder');
		await model.transaction(async()=>{
			try{
				let resorder = await model.where({id:id}).update({status:1,auditorid:this.userinfo.id});

				let goodsdata = []
				let goodsdatalog = []
				let fu = orderinfo.ordertype == 6 ? 1 : -1
				let ordertype
				switch (orderinfo.ordertype) {
					case 6:
						ordertype = 'RKD'
						break
					case 7:
						ordertype = 'CkD'
						break
				}

				for (var i = orderlist.length - 1; i >= 0; i--) {
					let goodsinfo = await this.model('or_goods').db(model.db()).where({id: orderlist[i].goodsid}).find();
					goodsinfo.nums += orderlist[i].num*fu
					// 判断是否允许负库存
					if (goodsinfo.nums < 0) {
						model.rollback()
						let goods = await this.model('or_goods').db(model.db()).where({id: goodsinfo.goodsid}).find()
						return this.fail(goods.name + "库存不足！")
					}
					goodsdata.push(goodsinfo)
					goodsdatalog.push({
						departmentid: orderinfo.departmentid,
						goodsid: orderlist[i].goodsid,
						ordertype: ordertype,
						orderid: id,
						nums: orderlist[i].num*fu,
						addtime: orderinfo.addtime,
						posttime: Math.round(Date.parse(new Date())/1000)
					})
				};

				let resgoods = await this.model('or_goods').db(model.db()).updateMany(goodsdata);
				let resgoodslog = await this.model('or_shop_goodslog').db(model.db()).addMany(goodsdatalog);

				if (resorder && resgoods && resgoodslog) {
					model.commit();
					return this.success({data:200, info:'操作成功！'});
				} else {
					model.rollback();
					return this.fail("操作失败！");
				}
			}catch(e){
				console.log(e)
				model.rollback();
				return this.fail("操作失败！");
			}
		})
	}

	async stockgoodslistAction(){
		let page = this.post();
		let pages = page.pages;
		let limits = page.limits;
		let search = page.search;
		let orid = this.userinfo.departmentid;

		let shoplist = await this.model('or_department').where({pid: orid}).select()

		// 制作表行
		let sql = ''
		shoplist.forEach(function(e){
			sql += 'sum(if(s.shopid = ' + e.id + ', s.nums, 0)) as "' + e.name + '_' + e.id + '", '
		})
		sql = sql.substr(0, sql.length - 2)

		let goodslist = await this.model('or_goods')
		.alias('g')
		.field('g.id,g.name,' + sql + ', sum(s.nums) as allnums, g.nums')
		.join('left join `think_or_shop_goods` s on g.id = s.goodsid')
		.where({'g.isdisabled': 0, 'g.departmentid': orid,'g.name': ['like', '%'+search+'%']})
		.group('g.id')
		.page(pages,limits)
		.order('g.id DESC')
		.select()

		let shops = await this.model('or_department').where({pid: orid}).select();

		let count = await this.model('or_goods')
		.alias('g')
		.join('left join `think_or_shop_goods` s on g.id = s.goodsid')
		.where({'g.isdisabled': 0, 'g.departmentid': orid})
		.count('distinct g.id')

		if (!think.isEmpty(goodslist)) {
			goodslist.forEach((row) => {
				row.allnums += row.nums
			})
		}

		let relist = {
      "data": goodslist,
      "count":count,
      'shoplist': shops
    }
		return this.json(relist)

	}
}